#!/usr/bin/env bash

WORK_DIR="$(dirname "$(pwd)")"

build_all() {
  # build backend
  cd "${WORK_DIR}/backend" || exit
  echo "cur: $(pwd)"
  # mvn clean && mvn package -DPROFILE=prod
  mvn clean install -P prod

  # build mqtt module
  cd "${WORK_DIR}/others/mqtt" || exit
  echo "cur: $(pwd)"
  # mvn clean && mvn package -DPROFILE=prod
  mvn clean install -P prod

  # build frontend
  cd "${WORK_DIR}/frontend" || exit
  source /etc/profile
  nvm use 16.15.0
  npm config set registry https://registry.npmmirror.com/
  [ -f dist ] && rm dist -rf
  npm install
  npm run build:prod
}

remove_image() {
  if [[ ! -z $(docker images | grep "$1") ]]; then
    echo "正在删除镜像$1:$2"
    docker rmi "$1:$2"
  fi
}

# 构建
build_all

# 进入工作目录
cd "${WORK_DIR}" || exit
# 停止并删除容器
docker compose down
# 删除镜像
remove_image "auth_app" "latest"
remove_image "backend_app" "latest"
echo "删除镜像结束"

# 删除历史数据
#rm /root/docker/influxdb -rf
#rm /root/docker/mysql -rf
rm /root/docker/redis -rf
rm /root/docker/emqx -rf

docker compose up -d